package com.wangzhen.spring.ioc.dependcy.loopup;

import com.wangzhen.spring.ioc.dependcy.annotation.MyBean;
import com.wangzhen.spring.ioc.dependcy.entity.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * 依赖查找示例：
 * 1、通过名称查找（实时+延迟ObjectFactory）
 * 2、通过类型查找（User.class, 根据类型查找一个bean,或者同一类型的多个bean）
 * 3、通过注解查找（查找标注了某个注解的多个bean）
 * @author dell
 * @since 2020/9/18 12:37
 */
public class DependcyLookupDemo {

    public static void main(String[] args) {
        BeanFactory factory = new ClassPathXmlApplicationContext("classpath:/META-INF/dependcy-lookup-context.xml");
        // 根据bean名称 实时查找
        lookUpBeanByNameInRealTime(factory);
        // 根据bean名称  延迟查找
        lookUpBeanByNameInLazy(factory);

        // 根据类型查找单个bean
        lookUpBeanByType(factory);
        // 根据类型查找同一类型的多个bean
        lookUpBeanByCollectionType(factory);

        // 通过注解查找bean
        lookUpBeanByAnnotation(factory);

        Environment bean = factory.getBean(Environment.class);
        System.out.println(bean);

    }

    private static void lookUpBeanByAnnotation(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory)beanFactory;
            Map<String, Object> userMap = listableBeanFactory.getBeansWithAnnotation(MyBean.class);
            System.out.println(userMap);
        }
    }

    /**
     * 根据名称-->实时查找
     * @param beanFactory
     */
    private static void lookUpBeanByNameInRealTime(BeanFactory beanFactory) {
        User user = (User)beanFactory.getBean("user");
        System.out.println(user);
    }

    /**
     * 根据名称-->实时查找
     * @param beanFactory
     */
    private static void lookUpBeanByNameInLazy(BeanFactory beanFactory) {
        ObjectFactory<User> objectFactory = (ObjectFactory<User>) beanFactory.getBean("objectFactory");
        System.out.println(objectFactory.getObject());
    }

    /**
     * 根据名称-->实时查找==单个bean
     * @param beanFactory
     */
    private static void lookUpBeanByType(BeanFactory beanFactory) {
        User bean = beanFactory.getBean(User.class);
        System.out.println("根据类型实时查找："+bean);
    }

    /**
     * 根据名称-->实时查找==返回的是同一类型的多个bean
     * @param beanFactory
     */
    private static void lookUpBeanByCollectionType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory)beanFactory;
            Map<String, User> userMap = listableBeanFactory.getBeansOfType(User.class);
            System.out.println(userMap);
        }
    }
}
